<template>
  <div class="header-box" >
    <div>
      <header class="w">
        <div class="w-box">
          <div class="nav-logo">
            <h1>
              <router-link to="/" title='商城官网'><a>数码商城</a></router-link>
            </h1>
          </div>
          <div class="right-box">
            <div class="nav-list">
              <el-autocomplete
                placeholder="请输入商品信息"
                suffix-icon="el-icon-search"
                style="width:305px"
                v-model="queryInfo.productInfo"
                :minlength = "1"
                :maxlength = "100"
                :fetch-suggestions="querySearchAsync"
                @select="handleSelect"
                @keydown.enter.native="handleIconClick">
                <template slot-scope="{ item }">
                  <div class="autocomplete-choose-name" v-html="htmlValue(item.value)"></div>
                </template>
              </el-autocomplete>
              <router-link to="/goods">
                <a @click="choosePage = 2">全部商品</a>
              </router-link>
              <router-link to='/thanks'>
                <a>感谢</a>
              </router-link>
            </div>
            <div class="nav-aside" :class="{fixed:st}">
              <div class="user pr">
                <router-link v-if="login" to="/user">个人中心</router-link>
                <router-link v-else to="/login"></router-link>
                <!--用户信息显示-->
                <div class="nav-user-wrapper pa" v-if="login">
                  <div class="nav-user-list">
                    <ul>
                      <!--头像-->
                      <li class="nav-user-avatar">
                        <div >
                          <span class="avatar">
                            <el-avatar v-if="userInfo.avatar" :size="50" :src="'http://127.0.0.1:8000/' + userInfo.avatar"></el-avatar>
                            <el-avatar v-else :size="50" src='https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'></el-avatar>
                          </span>
                          
                        </div>
                        <p class="name">{{ userInfo.nickname }}</p>
                      </li>
                      <li>
                        <router-link to="/user/orderList">我的订单</router-link>
                      </li>
                      <li>
                        <router-link to="/user/information">账号资料</router-link>
                      </li>
                      <li>
                        <router-link to="/user/addressList">收货地址</router-link>
                      </li>
                      <!-- <li>
                        <router-link to="/user/support">售后服务</router-link>
                      </li> -->
                      <li>
                        <a href="javascript:;" @click="logOut">退出</a>
                      </li>
                    </ul>
                  </div>
                </div>
              </div>
              <div class="shop pr" ref="positionMsg" @mouseenter="cartShowState(true)" @mouseleave="cartShowState(false)">
                <router-link to="/cart"></router-link>
                <span class="cart-num">
                  <i class="num" :class="{no:totalNum <= 0}">{{ totalNum }}</i>
                </span>
                <!-- 购物车显示 -->
                <div class="nav-user-wrapper pa active" v-if="showCart && login ">
                  <div class="nav-user-list">
                    <div class="full" v-if="cartList.length">
                      <!--购物列表-->
                      <div class="nav-cart-items">
                        <ul>
                          <li class="clearfix" v-for="cart in cartList" :key="cart.id">
                            <div class="cart-item">
                              <div class="cart-item-inner">
                                <a @click="productDetail(cart.goods_info.id)">
                                  <div class="item-thumb">
                                    <img :src="'http://127.0.0.1:8000/' +cart.goods_info.goods_Bigimg">
                                  </div>
                                  <div class="item-desc">
                                    <div class="cart-cell">
                                      <h4>
                                        <div style="color:#508EE4">{{ cart.goods_info.goods_name }}</div>
                                      </h4>
                                      <h6>
                                        <span class="price-icon">¥</span><span
                                        class="price-num">{{cart.goods_info.goods_price}}</span><span
                                        class="item-num">x {{cart.goods_number}}</span>
                                      </h6>
                                    </div>
                                  </div>
                                </a>
                                <div class="del" >
                                  <el-button type="danger" icon="el-icon-delete" circle @click="delGoods(cart.id)"></el-button>
                                </div>
                              </div>
                            </div>
                          </li>
                        </ul>
                      </div>
                      <!--总件数-->
                      <div class="nav-cart-total"><p>共 <strong>{{ totalNum }}</strong> 件商品</p> <h5>合计：<span
                        class="price-icon">¥</span><span
                        class="price-num">{{ totalPrice }}</span></h5>
                        <h6>
                          <el-button type="primary" @click="toCart">去购物车</el-button>
                        </h6>
                      </div>
                    </div>
                    <div style="height: 313px;text-align: center" class="cart-con" v-else>
                      <p>您的购物车竟然是空的!</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </header>
      <slot name="nav">
        <div class="nav-sub" :class="{fixed:st}">
          <div class="nav-sub-bg"></div>
          <div class="nav-sub-wrapper" :class="{fixed:st}">
            <div class="w">
              <ul class="nav-list2">
                <li>
                  <router-link to="/"><a @click="changGoods(1)" :class="{active:choosePage == 1}">首页</a></router-link>
                </li>
                <li>
                  <a @click="changGoods(2)" :class="{ active: choosePage == 2 }">全部</a>
                </li>
                <li v-for="item in typeList" :key="item.id">
                  <a @click="changGoods(item.id + 2)" :class="{active: choosePage == item.id + 2}">{{ item.goods_type }}</a>
                </li>
                <!-- <li>
                  <a @click="changGoods(4)" :class="{active: choosePage == 4}">电脑</a>
                </li>
                <li>
                  <a @click="changGoods(5)" :class="{active: choosePage == 5}">笔记本</a>
                </li>
                <li>
                  <a @click="changGoods(6)" :class="{active: choosePage == 6}">平板</a>
                </li>
                <li>
                  <a @click="changGoods(7)" :class="{active: choosePage == 7}">品牌周边</a>
                </li> -->
              </ul>
              <div></div>
            </div>
          </div>
        </div>
      </slot>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex"
import { getCartInfo, deleteCart } from '../api/cart'
import { getSearchGoodsInfo, getGoodsType } from '../api/goods'

export default{
  data() {
    return {
      // 商品的查询参数
      queryInfo: {
        productInfo: '',
        pageNum: 1,
        pageSize: 10,
        min: null,
        max: null,
        goodstype: 0,
        order: 0
      },
      // 搜索结果数组
      searchResults: [],
      st: false,
      choosePage: 1,
      // 商品类型列表
      typeList: []
    }
  },
  computed: {
    ...mapState(['login', 'userInfo', 'cartList', 'showCart']),
    totalNum() {
      return this.cartList && this.cartList.reduce((total, item) => {
         return total += item.goods_number
      },0)
    },
    totalPrice() {
      return this.cartList && this.cartList.reduce((total, item) => {
        return total += item.goods_number * item.goods_info.goods_price
      },0)
    }
  },
  created() {
    if(this.login){
      this.getCartInfo()
    }
    this.getType()
  },
  methods:{
    ...mapMutations(['SHOWCART', 'CARTINFO']),
    async getCartInfo() {
      const { data: res } = await getCartInfo()

      if(res.code !== 0 ) {
        return this.$notify.error({
          title: '警告',
          message: '获取购物车信息失败'
        })
      }
      this.CARTINFO(res.result.list)
    },
    // 获取商品类型
    async getType() {
      const { data: res } = await getGoodsType(this.queryInfo)

      res.result.list.map(item => {
        if(item.id !== 5) {
          this.typeList.push(item)
        }
      })
    },
    // 查看商品详情
    productDetail(id) {
      window.open('//' + window.location.host + `/#/goodsDetail/${Number(id)}`)
    },
    // 删除购物车商品
    async delGoods(id) {
      // 弹框确认用户是否删除数据
      const confirmResult = await this.$confirm('确认将这1个宝贝删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).catch(err => err)

      // 如果用户确认删除，则返回字符串 confirm,取消则是 cancel
      if (confirmResult !== 'confirm') {
        return 
      }
      
      const { data: res } = await deleteCart({ids: [id]})
      if(res.code !== 0 ) {
        return this.$notify.error({
          title: '警告',
          message: '删除购物车商品失败'
        })
      }
      this.getCartInfo()
    },
    // 前往购物车页面
    async toCart() {
      this.$router.push('/cart')
    },
    changePage (v) {
      this.choosePage = v
    },
    changGoods (v) {
      this.changePage(v)
      if (v === 1) {
        this.$router.push({
          path: '/'
        })
      } else if (v === 2) {
        this.$router.push({
          path: '/goods'
        })
      } else {
        this.$router.push({
          path: `/goods?type=${v-2}`
        })
      }
    },
    // 控制顶部
    navFixed () {
      if (this.$route.matched[0].path === '/user' || this.$route.path === '/cart' || this.$route.matched[0].path === '/order' || this.$route.path === '/checkout' || this.$route.path === '/search'){
        return false
      }
      const st = document.documentElement.scrollTop || document.body.scrollTop
      // console.log(st)
      st >= 100 ? this.st = true : this.st = false
    },
    // 控制购物车的显示
    cartShowState(state) {
      this.SHOWCART({ showCart: state })
      // console.log(this.cartList)
    },
    // 退出登录
    logOut() {
      window.sessionStorage.clear()
      this.$router.push('/home')
      this.$router.go(0)
    },
    // 前往搜索商品的页面
    handleIconClick () {
      if (this.$route.path === '/search') {
        this.$router.push({
          path: '/refreshsearch',
          query: {
            key: this.queryInfo.productInfo
          }
        })
      } else {
        this.$router.push({
          path: '/search',
          query: {
            key: this.queryInfo.productInfo
          }
        })
      }
    },
    // 关键字高亮
    htmlValue(val) {
      let key = this.queryInfo.productInfo;
      if (key.length > 0) {
        return val.replace( 
        new RegExp(key, "gi"),
        "<span style='color:red;'>" + key + "</span>"
        )
      }
      return val
    },
    // 搜索框提示
    async loadAll () {
      const { data: res} = await getSearchGoodsInfo(this.queryInfo)

      if(res.code !== 0) {
        return this.$notify.error({
          title: '警告',
          message: '获取搜索商品信息失败'
        })
      }

      if (res.result.list === null || res.result.list === '') {
        return
      }

      let array = []
      let maxSize = 5
      if (res.result.list.length <= 5) {
        maxSize = res.result.list.length
      }
      for (let i = 0; i < maxSize; i++) {
        let obj = {}
        obj.value = res.result.list[i].goods_name
        array.push(obj)
      }
      if (array.length !== 0) {
        this.searchResults = array
      } else {
        this.searchResults = []
      }
      // console.log(res)
    },
    querySearchAsync (queryString, cb) {
      if (this.queryInfo.productInfo === undefined) {
        cb([])
        return
      }
      this.queryInfo.productInfo = this.queryInfo.productInfo.trim()
      if (this.queryInfo.productInfo === '') {
        cb([])
        return
      } else {
        this.loadAll()
        setTimeout(() => {
          cb(this.searchResults)
        }, 300)
      }
    },
    handleSelect (item) {
      this.queryInfo.productInfo = item.value
      this.handleIconClick()
    },
  },
  mounted () {
    this.navFixed()
    window.addEventListener('scroll', this.navFixed)
    window.addEventListener('resize', this.navFixed)
  },
}
</script>

<style lang="scss" scoped>
  @import "../assets/style/theme.scss";
  @import "../assets/style/mixin.scss";

  .header-box {
    background: $head-bgc;
    background-image: -webkit-linear-gradient(#000, #121212);
    background-image: linear-gradient(#000, #121212);
    width: 100%;

  }

  header {
    height: 100px;
    z-index: 30;
    position: relative;
  }

  .w-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100%;
    // position: relative;
    h1 {
      height: 100%;
      display: flex;
      align-items: center;
      > a {
        background: url(../assets/img/bz.jpg) no-repeat 50%;
        border-radius: 50%;
        background-size: cover;
        display: block;
        @include wh(60px, 60px);
        text-indent: -9999px;
        background-position: 0 0;
      }
    }
    .nav-list {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 22px;
      .el-input{
        width: 305px;
      }
      a {
        width: 110px;
        color: #c8c8c8;
        display: block;
        font-size: 14px;
        padding: 0 25px;
        &:hover {
          color: #fff;
        }
      }
      a:nth-child(2){
        margin-left: -10px;
      }
    }
    .nav-aside {
      position: relative;
      &:before {
        background: #333;
        background: hsla(0, 0%, 100%, .2);
        content: " ";
        @include wh(1px, 13px);
        overflow: hidden;
        // position: absolute;
        display: flex;
        align-items: center;
        // top: 4px;
        left: 0;
      }
      &.fixed {
        width: 262px;
        position: fixed;
        left: 50%;
        top: 19px;
        margin-left: 451px;
        margin-top: 0;
        z-index: 32;
        top: -40px;
        -webkit-transform: translate3d(0, 59px, 0);
        transform: translate3d(0, 59px, 0);
        -webkit-transition: -webkit-transform .3s cubic-bezier(.165, .84, .44, 1);
        transition: transform .3s cubic-bezier(.165, .84, .44, 1);
        .user {
          &:hover {
            a:before {
              background-position: -215px 0;
            }
          }
        }
        .shop {
          &:hover {
            a:before {
              background-position: -210px -22px;
            }
          }
        }
      }
    }

    .right-box {
      display: flex;
    }
    .nav-aside {
      display: flex;
      align-items: center;
    }
    // 用户
    .user {
      margin-left: 41px;
      width: 36px;
      &:hover {
        a:before {
          background-position: -5px 0;
        }
        .nav-user-wrapper {
          top: 18px;
          visibility: visible;
          opacity: 1;
          -webkit-transition: opacity .15s ease-out;
          transition: opacity .15s ease-out;
        }
      }
      > a {
        position: relative;
        @include wh(36px, 20px);
        display: block;
        text-indent: -9999px;
        &:before {
          content: " ";
          position: absolute;
          left: 8px;
          top: 0;
          @include wh(20px);
          background: url(../assets/img/account-icon@2x.32d87deb02b3d1c3cc5bcff0c26314ac.png) -155px 0;
          background-size: 240px 107px;
          transition: none;
        }

      }
      li + li {
        text-align: center;
        position: relative;
        border-top: 1px solid #f5f5f5;
        line-height: 44px;
        height: 44px;
        color: #616161;
        font-size: 12px;
        &:hover {
          background: #fafafa;
        }
        a {
          display: block;
          color: #616161;
        }
      }
      .nav-user-avatar {
        > div {
          position: relative;
          margin: 0 auto 8px;
          @include wh(46px);
          text-align: center;
          /* &:before {
            content: "";
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            border-radius: 50%;
            box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .06);
          } */
          .avatar {
            margin-left: -2px;
          }
        }
        .name {
          margin-bottom: 16px;
          font-size: 12px;
          line-height: 1.5;
          text-align: center;
          color: #757575;
        }
      }
      .nav-user-wrapper {
        width: 168px;
        transform: translate(-50%);
        left: 50%;
      }
      .nav-user-list {
        width: 168px;
        &:before {
          left: 50%;
        }

      }
    }
    .shop {
      position: relative;
      float: left;
      margin-left: 21px;
      width: 61px;
      z-index: 99;
      &:hover {
        a:before {
          content: " ";
          background-position: 0 -22px;
        }
      }
      .nav-user-wrapper.active {
        top: 18px;
        visibility: visible;
        opacity: 1;
        -webkit-transition: opacity .15s ease-out;
        transition: opacity .15s ease-out;
      }
      > a {
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        display: block;
        right: 0;
        z-index: 1;
        &:before {
          display: block;
          @include wh(30px, 100%);
          content: " ";
          background: url(../assets/img/account-icon@2x.32d87deb02b3d1c3cc5bcff0c26314ac.png) 0 -22px;
          background-size: 240px 107px;
          background-position: -150px -22px;
        }
      }
      .cart-num {
        position: relative;
        display: block;
        margin-left: 31px;
        margin-top: -1px;
        min-width: 30px;
        text-indent: 0;
        line-height: 20px;
        > i {
          background: #eb746b;
          background-image: -webkit-linear-gradient(#eb746b, #e25147);
          background-image: linear-gradient(#eb746b, #e25147);
          box-shadow: inset 0 0 1px hsla(0, 0%, 100%, .15), 0 1px 2px hsla(0, 0%, 100%, .15);
          text-align: center;
          font-style: normal;
          display: inline-block;
          @include wh(20px);
          line-height: 20px;
          border-radius: 10px;
          color: #fff;
          font-size: 12px;
          &.no {
            background: #969696;
            background-image: -webkit-linear-gradient(#A4A4A4, #909090);
            background-image: linear-gradient(#A4A4A4, #909090);
            box-shadow: inset 0 0 1px #838383, 0 1px 2px #838383;
          }
        }

      }
      .nav-user-wrapper {
        right: 0;
        width: 360px;
        .nav-user-list {
          &:before {
            right: 34px;
          }
        }
      }
      .nav-user-list {
        padding: 0;
        width: 100%;
        .full {
          border-radius: 8px;
          overflow: hidden;
        }
        .nav-cart-items {
          max-height: 363px;
          overflow-x: hidden;
          overflow-y: auto;
        }
        .cart-item {
          height: 120px;
          width: 100%;
          overflow: hidden;
          border-top: 1px solid #f0f0f0;
          &:hover {
            background: #fcfcfc;
            .del {
              display: block;
            }
          }

        }
        li:first-child .cart-item:first-child {
          border-top: none;
          border-radius: 8px 8px 0 0;
          overflow: hidden;
        }
        .cart-item-inner {
          padding: 20px;
          position: relative;
        }
        .item-thumb {
          position: relative;
          float: left;
          width: 80px;
          height: 80px;
          border-radius: 3px;
          &:before {
            content: "";
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            z-index: 2;
            border: 1px solid #f0f0f0;
            border: 0 solid transparent;
            box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .06);
            border-radius: 3px;
          }
          img {
            display: block;
            @include wh(80px, 80px);
            border-radius: 3px;
            overflow: hidden;
          }
        }
        .item-desc {
          margin-left: 98px;
          display: table;
          @include wh(205px, 80px);
          h4 {
            color: #000;
            width: 185px;
            overflow: hidden;
            word-break: keep-all;
            white-space: nowrap;
            text-overflow: ellipsis;
            font-size: 14px;
            line-height: 16px;
            margin-bottom: 10px;
          }
          .attrs span {
            position: relative;
            display: inline-block;
            margin-right: 20px;
            font-size: 14px;
            line-height: 14px;
            color: #999;
          }
          .attrs span:last-child {
            margin-right: 0;
          }
          h6 {
            color: #cacaca;
            font-size: 12px;
            line-height: 14px;
            margin-top: 20px;
            span {
              display: inline-block;
              font-weight: 700;
              color: #cacaca;
            }
            .price-icon, .price-num {
              color: #d44d44;
            }
            .price-num {
              margin-left: 5px;
              font-size: 14px;
            }
            .item-num {
              margin-left: 10px;
            }
          }

        }
        .cart-cell {
          display: table-cell;
          vertical-align: middle;
        }
        .del {
          display: none;
          overflow: hidden;
          position: absolute;
          right: 20px;
          top: 50%;
          transform: translateY(-50%);
        }
      }
      .nav-cart-total {
        box-sizing: content-box;
        position: relative;
        padding: 20px;
        height: 40px;
        background: #fafafa;
        border-top: 1px solid #f0f0f0;
        border-radius: 0 0 8px 8px;
        box-shadow: inset 0 -1px 0 hsla(0, 0%, 100%, .5), 0 -3px 8px rgba(0, 0, 0, .04);
        background: -webkit-linear-gradient(#fafafa, #f5f5f5);
        background: linear-gradient(#fafafa, #f5f5f5);
        p {
          margin-bottom: 4px;
          line-height: 16px;
          font-size: 12px;
          color: #c1c1c1;
        }
        h5 {
          line-height: 20px;
          font-size: 14px;
          color: #6f6f6f;
          span {
            font-size: 18px;
            color: #de4037;
            display: inline-block;
            font-weight: 700;
          }
          span:first-child {
            font-size: 12px;
            margin-right: 5px;
          }
        }
        h6 {
          position: absolute;
          right: 20px;
          top: 20px;
          width: 108px;
        }
      }
    }
  }

  @media (max-height: 780px) {
    .nav-cart-items {
      max-height: 423px !important;
    }
  }

  @media (max-height: 900px) {
    .nav-cart-items {
      max-height: 544px !important;
    }
  }

  @media (max-height: 1080px) {
    .nav-cart-items {
      max-height: 620px !important;
    }
  }

  // 用户信息弹出
  .nav-user-wrapper {
    position: absolute;
    z-index: 30;
    padding-top: 18px;
    opacity: 0;
    visibility: hidden;
    top: -3000px;
    .nav-user-list {
      position: relative;
      padding-top: 20px;
      background: #fff;
      border: 1px solid #d6d6d6;
      border-color: rgba(0, 0, 0, .08);
      border-radius: 8px;
      box-shadow: 0 20px 40px rgba(0, 0, 0, .15);
      z-index: 10;
      &:before {
        position: absolute;
        content: " ";
        background: url(../assets/img/account-icon@2x.32d87deb02b3d1c3cc5bcff0c26314ac.png) no-repeat -49px -43px;
        background-size: 240px 107px;
        @include wh(20px, 8px);
        top: -8px;
        margin-left: -10px;
      }
    }
  }

  .nav-sub {
    position: relative;
    z-index: 20;
    height: 75px;
    background: #f7f7f7;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .04);
    &.fixed {
      position: fixed;
      z-index: 21;
      height: 60px;
      top: 0;
      left: 0;
      right: 0;
      border-bottom: 1px solid #dadada;
      background-image: -webkit-linear-gradient(#fff, #f1f1f1);
      background-image: linear-gradient(#fff, #f1f1f1);
    }
    .nav-sub-wrapper {
      padding: 25px 0;
      height: 75px;
      position: relative;
      &.fixed {
        padding: 0;
        height: 100%;
        display: flex;
        align-items: center;
      }
      &:after {
        content: " ";
        position: absolute;
        top: 89px;
        left: 50%;
        margin-left: -610px;
        width: 1220px;
        background: #000;
        height: 1px;
        display: none;
        opacity: 0;
        -webkit-transition: opacity .3s ease-in;
        transition: opacity .3s ease-in;
      }
    }
    .w {
      display: flex;
      justify-content: space-between;
    }
    .nav-list2 {
      height: 28px;
      line-height: 28px;
      display: flex;
      align-items: center;
      height: 100%;
      li:first-child {
        padding-left: 0;
        a {
          padding-left: 10px;
        }
      }
      li {
        position: relative;
        float: left;
        padding-left: 3px;
        a {
          display: block;
          padding: 0 10px;
          color: #666;
          &.active {
            font-weight: bold;
          }
        }
        a:hover {
          color: #5683EA;
        }
      }
      li:before {
        content: ' ';
        position: absolute;
        left: 0;
        top: 13px;
        width: 2px;
        height: 2px;
        background: #bdbdbd;
      }
    }
  }

  @media (min-width: 1px) {
    .nav-sub .nav-sub-wrapper:after {
      display: block;
    }
  }

  .cart-con {
    /*display: flex;*/
    text-align: center;
    position: relative;
    p {
      padding-top: 185px;
      color: #333333;
      font-size: 16px;
    }
  }

  .cart-con:before {
    position: absolute;
    content: ' ';
    left: 50%;
    transform: translate(-50%, -70%);
    top: 50%;
    width: 76px;
    height: 62px;
    background: url("../assets/img/cart-empty-new.png") no-repeat;
    background-size: cover;

  }
</style>

